package com.jxtc.enterprise.delivery.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jxtc.enterprise.common.constants.OrderPaymentStatus;
import com.jxtc.enterprise.common.entity.Company;
import com.jxtc.enterprise.common.entity.DeliveryTaskTemplate;
import com.jxtc.enterprise.common.entity.OrderDetail;
import com.jxtc.enterprise.common.entity.OrderPayment;
import com.jxtc.enterprise.common.mapper.*;
import com.jxtc.enterprise.delivery.vo.verifyOrder.VerifyOrderDetailVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class RiderVerifyOrderService {

    /**
     * 核销页面，根据取餐码查询订单时，是否只查询某个骑手负责配送的订单，true表示仅在该骑手配送的订单查询；false 表示在所有订单中查询
     */
    @Value("${pickup.verify.onlyShowRiderOwnedOrder:false}")
    private boolean pickUpVerifyOnlyShowRiderOwnedOrder;

    private final OrderDetailMapper orderDetailMapper;
    private final OrderMapper orderMapper;
    private final RiderMapper riderMapper;
    private final DeliveryTaskTemplateMapper deliveryTaskTemplateMapper;
    private final CompanyMapper companyMapper;

    public List<VerifyOrderDetailVO> queryOrderDetailsByPickupCode(String riderId, Integer pickupCode) {

        List<String> companyIdList = null;
        if (pickUpVerifyOnlyShowRiderOwnedOrder) {
            // 获取骑手负责的公司 ID 列表
            LambdaQueryWrapper<DeliveryTaskTemplate> queryWrapper = new LambdaQueryWrapper<DeliveryTaskTemplate>()
                    .eq(DeliveryTaskTemplate::getDelFlag, false)
                    .eq(DeliveryTaskTemplate::getRiderId, riderId)
                    .select(DeliveryTaskTemplate::getCompanyId);
            companyIdList = deliveryTaskTemplateMapper.selectObjs(queryWrapper);
            if (companyIdList.isEmpty()) {
                // 如果该骑手没有负责配送的公司，那么向前端返回错误提示信息
                throw new IllegalArgumentException("ID 为 " + riderId + " 的骑手没有负责的公司");
            }
        }

        LocalDate today = LocalDate.now();
        String dateFlag = today.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        // 取餐码可能重复，所以返回的订单支付列表可能包含多个订单
        // 配置项 pickup.verify.onlyShowRiderOwnedOrder未false时，companyIdList 为null，此时查询订单时，不限定订单所属的公司id，在所有订单中查询
        List<OrderPayment> orderPaymentList = orderMapper.queryOrderByPickupCodeAndCompanyIds(pickupCode, dateFlag, companyIdList);
        if (orderPaymentList.isEmpty()) {
            // 如果没有找到订单，那么向前端返回错误提示信息
            log.warn("取餐码为 {} 的订单不存在", pickupCode);
            return new ArrayList<>();
        }

        List<String> orderIdList = orderPaymentList.stream()
                .map(OrderPayment::getId)
                .collect(Collectors.toList());

        LambdaQueryWrapper<OrderDetail> orderDetailQueryWrapper = new LambdaQueryWrapper<OrderDetail>()
                .in(OrderDetail::getOrderId, orderIdList);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(orderDetailQueryWrapper);

        // 将订单详情根据订单 ID 分组
        Map<String, List<OrderDetail>> orderMap = orderDetailList.stream()
                .collect(Collectors.groupingBy(OrderDetail::getOrderId));

        List<VerifyOrderDetailVO> voList = new ArrayList<>();
        for (OrderPayment orderPayment : orderPaymentList) {
            String orderId = orderPayment.getId();
            List<OrderDetail> orderDetails = orderMap.get(orderId);

            VerifyOrderDetailVO vo = new VerifyOrderDetailVO();
            vo.setOrderId(orderId);
            vo.setUserId(orderPayment.getUserId());
            vo.setPhone(orderPayment.getPhone());
            vo.setCompanyId(orderPayment.getCompanyId());

            // 一份订单中的订单详情中，保存的用户名一定一致，任意取一个即可
            String userName = orderDetails.stream().map(OrderDetail::getUsername)
                    .findAny()
                    .orElse("无");
            String foodId = orderDetails.stream().map(OrderDetail::getFoodId).collect(Collectors.joining(","));
            vo.setFoodId(foodId);
            vo.setUserName(userName);
            // 查询订单所属用户的公司信息，获取订单所属用户的公司名称
            Company companyInfo = companyMapper.selectOne(
                    new LambdaQueryWrapper<Company>()
                            .eq(Company::getDelFlag, false)
                            .eq(Company::getId, orderPayment.getCompanyId()));
            if (companyInfo == null) {
                log.error("订单: {}, 所属用户: {} 的公司id: {}, 无法查询到公司详情",
                        orderId, orderPayment.getUserId(), orderPayment.getCompanyId());
                vo.setCompanyName("未知");
            } else {
                vo.setCompanyName(companyInfo.getName());
            }

            // 如果用户在一份订单中点了多份订单详情（菜品），则通过 ", " 拼接菜名
            String foodPrintName = orderDetails.stream().map(OrderDetail::getFoodPrintName)
                    .collect(Collectors.joining(", "));
            vo.setFoodPrintName(foodPrintName);

            int verifyStatus = 0;
            if (OrderPaymentStatus.TO_SEND.getValue() == orderPayment.getStatus()
                    || OrderPaymentStatus.TO_RECEIVE.getValue() == orderPayment.getStatus()) {
                // status为 2，或为 3 的，核销状态为 "未核销"
                verifyStatus = 1;
            } else if (OrderPaymentStatus.COMPLETED.getValue() == orderPayment.getStatus()) {
                // status为 8，状态为 "已核销"
                verifyStatus = 2;
            } else {
                verifyStatus = 3; // 无效
                log.warn("订单: {} 状态: {}, 核销状态为：无效(3)", orderId, orderPayment.getStatus());
            }
            vo.setVerifyStatus(verifyStatus);

            voList.add(vo);
        }

        return voList;
    }

    @Transactional
    public void confirmUserOrderReceived(String orderId) {
        OrderPayment savedorderPayment = orderMapper.selectById(orderId);
        if (savedorderPayment == null) {
            throw new IllegalArgumentException("ID 为 " + orderId + " 的订单不存在");
        }

        LambdaQueryWrapper<OrderDetail> orderDetailQueryWrapper = new LambdaQueryWrapper<OrderDetail>()
                .eq(OrderDetail::getOrderId, orderId)
                .select(OrderDetail::getId);
        List<String> orderDetailIdList = orderDetailMapper.selectObjs(orderDetailQueryWrapper);
        if (orderDetailIdList.isEmpty()) {
            // 如果订单对应的订单详情不存在，说明该订单数据也是不应该存在的
            throw new IllegalArgumentException("ID 为 " + orderId + " 的订单不存在");
        }

        // 更新订单状态为 "已完成"
        OrderPayment orderPayment = new OrderPayment();
        orderPayment.setId(orderId);
        orderPayment.setStatus(OrderPaymentStatus.COMPLETED.getValue());
        orderMapper.updateById(orderPayment);

        // 更新订单详情状态为 "已完成"
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setStatus(OrderPaymentStatus.COMPLETED.getValue());
        LambdaUpdateWrapper<OrderDetail> updateWrapper = new LambdaUpdateWrapper<OrderDetail>()
                .in(OrderDetail::getId, orderDetailIdList);
        orderDetailMapper.update(orderDetail, updateWrapper);
    }
}